<template>
    <div class="min-h-screen flex flex-col items-center justify-center">
        <header class="header bg-white p-4 shadow-md flex justify-between items-center">

            <div class="container flex items-center">
                <div class="links-container"> <!-- 新增的容器 -->
                    <a href="#" class="flex items-center text-gray-600 hover:text-blue-500">
                        <i class="icon-download"></i>
                        <span class="ml-1">下载App</span>
                    </a>
                    <a href="#" class="text-blue-500 font-bold hover:underline">栏目收费说明</a>
                </div>
                <!-- 使用 v-if/v-else 来条件渲染登录/注册按钮或用户信息 -->
                <div v-if="!username" class="lrcs items-center space-x-4"> <!-- Flex 布局让内容一行排列 -->
                    <RouterLink class="btn-login" to='/login'>登录</RouterLink>
                    <RouterLink class="btn-register" to='/register'>注册</RouterLink>
                </div>
                <div v-else class="user-info flex items-center space-x-3"> <!-- 用户信息 -->
                    <img :src="avatar" alt="用户头像" class="user-avatar w-8 h-8 rounded-full" />
                    <span>{{ username }}</span>
                    <span class="text-logout" @click="logout">退出</span>
                </div>

            </div>
        </header>

        <div class="search-header">
            <h1 class="text-a">丁香医生</h1>
            <form @submit.prevent="handleSearch" class="search-wrapper">
                <input v-model="searchQuery" type="text" placeholder="搜索疾病、医院、药品" class="search-input" />
                <button type="submit" class="search-button flex items-center justify-center gap-2">
                    <i class="icon-search"></i>
                    搜索
                </button>
            </form>
        </div>

        <!-- 顶部导航栏（大方框按钮样式）-->
        <TopNav :navItems="defaultNavItems" class="top-nav-custom" />

        <!-- 分类表 -->

        <DiseaseClassification />

        <!-- 医生表 -->
        <DoctorSection />

        <!-- 问答 -->
        <QAView />

        <!-- 文章 -->
        <MessageView />

        <!-- 底部导航栏 -->
        <div id="j-dxy-bottom" class="bottom-links">
            <a target="_blank" href="http://www.dxy.cn/pages/copyright.html" rel="nofollow">版权声明</a>
            <a target="_blank" href="https://dxy.com/column/board" rel="nofollow">作者编委</a>
            <a target="_blank" href="https://ask.dxy.com/ama/index" rel="nofollow">丁香医生</a>
            <a href="mailto: doctor@dxy.com" rel="nofollow">投稿邮箱 doctor@dxy.com</a>
            <a target="_blank">客服电话：0571-22931767</a>
        </div>
        <div class="bottom-links">
            <span class="bottom-line-item">Copyright © 2000-<span class="j-dxy-bottom-copyright-year">2024</span> DXY
                All Rights Reserved</span>
            <a id="record" class="bottom-line-item" target="_blank" href="https://beian.miit.gov.cn/"
                rel="nofollow">浙B2-20070219</a>
            <span class="bottom-line-item" rel="nofollow">浙卫(03)网审[2015] 048号</span>
            <span class="bottom-line-item">医疗器械网络销售备案编号：(浙杭)网械企备字[2018]第00246号</span>
        </div>
        <div class="bottom-links">
            <span class="bottom-line-item" rel="nofollow">第二类医疗器械经营备案凭证：浙杭食药监械经营备20153170号</span>
            <span class="bottom-line-item" rel="nofollow">网络文化经营许可证：浙网文[2018]11330-875号</span>
            <span class="bottom-line-item" rel="nofollow">食品许可证编号：JY13301080010985</span>
        </div>
        <div class="bottom-links">
            <span class="bottom-line-item" rel="nofollow">出版物经营许可证：新出发滨字第0064号</span>
            <span class="bottom-line-item" rel="nofollow">人力资源许可证编号：330108202110270036 号</span>
            <a class="bottom-line-item" target="_blank"
                href="https://img1.dxycdn.com/2022/0407/759/1810165994073381453-2.png" rel="nofollow">(浙)
                -经营性-2022-0039</a>
        </div>
        <div class="bottom-links">
            <span class="bottom-line-item" rel="nofollow">违法和不良信息举报电话：0571-28182622</span>
            <span class="bottom-line-item" rel="nofollow">举报邮箱：dxys@dxy.cn</span>
            <a class="bottom-line-item" rel="nofollow" target="_blank"
                href="https://assets.dxycdn.com/gitrepo/dxy-common-bottom/dist/report.html?t=1626775430995">涉未成年人违法和不良信息举报专区</a>
        </div>
        <div class="bottom-links">
            <img class="bottom-line-icon" src="https://assets.dxycdn.com/app/dxydoctor/img/ghs.png">
            <a class="bottom-line-item" target="_blank"
                href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=33010802004205" rel="nofollow">浙公网安备
                33010802004205号</a>
        </div>
        <div class="bottom-links">
            <a target="_blank" style="width: 35px" referrerpolicy="origin-when-cross-origin"
                href="http://idinfo.zjamr.zj.gov.cn/bscx.do?method=lzxx&amp;id=3301083301020000068855">
                <img src="https://img1.dxycdn.com/2020/1230/190/6618814823342006543-2.gif">
            </a>
            <a target="_blank" rel="nofollow me noopener noreferrer" style="margin-left: 10px; width: 35px"
                href="http://gcdthy.komect.com:18081/cloudsurvey/qaiuhxlh">
                <img src="https://img1.dxycdn.com/2021/0402/103/4090759592270723743-2.jpg">
            </a>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { jwtDecode } from "jwt-decode";
import { useRouter } from "vue-router";
import axios from "axios";
import TopNav from "../components/TopNav.vue";
import DiseaseClassification from "../components/DiseaseClassification.vue"
import DoctorSection from "../components/DoctorSection.vue";
import QAView from "../components/QAView.vue";
import MessageView from "../components/MessageView.vue";

interface NavItem {
    id: number;
    name: string;
    description: string;
    link: string;
}

const username = ref<string | null>(null);
const avatar = ref<string | null>(null);


const defaultNavItems: NavItem[] = [
    { id: 1, name: '问医生', description: '三甲主治在线', link: '/sections' },
    { id: 2, name: '查疾病', description: '权威疾病百科', link: '/disease' },
    { id: 3, name: '查药品', description: '药品信息大全', link: '/medicine' },
    { id: 4, name: '查医院', description: '国内医院信息查询', link: '/hospital' },
    { id: 5, name: '查检查/手术', description: '检查与手术专业百科', link: '/examination' },
    { id: 6, name: '查疫苗', description: '疫苗接种与禁忌', link: '/vaccine' },
    { id: 7, name: '急救指南', description: '急救知识百科查询', link: '/emergency' },
    { id: 8, name: '测一测', description: '1分钟了解自己', link: '/test' },
    { id: 9, name: '科普视频', description: '生活解惑与科普', link: '/videos' },

];

// let user = ref({})

// 判断用户的token是否过期，过期则清除token
const isTokenExpired = () => {
    const token = localStorage.getItem('token');
    if (token) {
        const payload = JSON.parse(atob(token.split('.')[1]));
        return new Date().getTime() > payload.exp * 1000;
    }
}

// 判断refresh_token是否过期
const isRefreshTokenExpired = () => {
    const refresh_token = localStorage.getItem('refresh_token');
    if (refresh_token) {
        const payload = JSON.parse(atob(refresh_token.split('.')[1]));
        return new Date().getTime() > payload.exp * 1000;

    }
}


// 如果access_token过期，则清除token，请求刷新token
const refreshToken = async () => {

    if (isRefreshTokenExpired()) {
        localStorage.removeItem('refresh_token');
        logout();
        
    }
    else {
        if (isTokenExpired()) {
            axios.post('http://127.0.0.1:8000/user/refresh/', {
                refresh: localStorage.getItem('refresh_token')

            }).then(res => {
                localStorage.setItem('token', res.data.access);
                fetchUserInfo();
            }).catch(err => {
                console.log(err);
                logout();
            })

        }
    }
}

    // 获取用户信息
    // const fetchUserInfo = async () => {
    //     const token = localStorage.getItem('token');
    //     if (token) {
    //         const payload = JSON.parse(atob(token.split('.')[1]));
    //         const userId = payload.id; // 获取用户ID

    //         const response = await fetch(`http://127.0.0.1:8000/user/userinfo/${userId}/`, {
    //             headers: { 'Authorization': `Bearer ${token}` }
    //         });
    //         const data = await response.json();
    //         username.value = data.username;
    //         avatar.value = data.avatar;
    //     }
    // };
const fetchUserInfo = async () => {
    const token = localStorage.getItem('token');
    if (token) {
        const payload = ref<any>(jwtDecode(token));
        username.value = payload.value.username;
        avatar.value = 'http://127.0.0.1:8000/uploads/' + payload.value.avatar;
        console.log(avatar.value);
    }

}

    // 注销用户
const logout = () => {
    username.value = null;
    avatar.value = null;
    clearTokenInBrowser(); // 假设这个函数清除token
};

const clearTokenInBrowser = () => {
    localStorage.removeItem('token');
};
    


// 搜索
const router = useRouter();
const searchQuery = ref('');
const handleSearch = () => {
    if (searchQuery.value.trim()) {
        router.push({
            path: '/search',
            query: { q: searchQuery.value }
        });
    }
};


// 页面挂载时获取用户信息
onMounted(() => {
    fetchUserInfo();

    if (isTokenExpired()) {
        logout();

    }

    if (isRefreshTokenExpired()) {
        refreshToken();
    }


});





</script>

<style scoped>
.btn-primary {
    margin-right: 10px;
}

/* 顶部导航调整 */
.top-nav-custom {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 8px;
    margin-bottom: 24px;
}

.top-nav-custom .nav-item {
    padding: 10px 20px;
    font-size: 16px;
    background-color: #f0f0f0;
    border-radius: 8px;
    text-align: center;
}

.top-nav-custom .nav-item:first-child {
    flex: 1 1 200px;
    background-color: #e0e0e0;
}

/* 底部链接样式 */
.bottom-links {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 8px;
    margin-top: 24px;
}

.bottom-links a {
    padding: 4px 8px;
    border-radius: 4px;
    text-decoration: none;
    color: #666;
}

.bottom-links a:hover {
    background-color: #f0f0f0;
}

.text-a {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 8px;
    margin-top: 24px;
    font-size: 32px;
    font-weight: 700;
    color: #00b38a;
}

/* 搜索 */
.search-header {
    background-color: #fff;
    padding: 20px 0;
    margin-bottom: 20px;
}

.search-wrapper {
    max-width: 600px;
    margin: 0 auto;
    display: flex;
    gap: 10px;
}

.search-input {
    flex: 1;
    padding: 12px 20px;
    border: 2px solid #00b38a;
    border-radius: 24px;
    font-size: 16px;
}

.search-button {
    padding: 12px 30px;
    background-color: #00b38a;
    color: white;
    border: none;
    border-radius: 24px;
    cursor: pointer;
    font-size: 16px;
}

/* 登录注册 */
/* 登录注册 */
/* Header Styling */
.header {
    background-color: #ffffff;
    /* White background */
    color: #333333;
    /* Gray text color */
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    /* Subtle shadow */
    padding: 16px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
}

/* Left Content Links */
.header a {
    text-decoration: none;
    color: #666666;
    font-size: 14px;
    display: flex;
    align-items: center;
    transition: color 0.3s ease;
}

.header a:hover {
    color: #00b38a;
    /* Match green color on hover */
}

.header a.text-blue-500 {
    color: #00b38a;
    /* Green color for special links */
    font-weight: bold;
    margin-left: 16px;
}

.text-logout {
    margin-left: 16px;
    background-color: transparent;
    /* 透明背景 */
    border: none;
    /* 无边框 */
    color: #666666;
    /* 文本颜色与下载链接一致 */
    padding: 0;
    /* 移除内边距 */
    font-size: 14px;
    font-weight: normal;
    /* 正常字体粗细 */
    cursor: pointer;
    text-decoration: none;
    /* 移除下划线 */
    transition: color 0.3s ease;
    /* 颜色过渡效果 */
}

.text-logout:hover {
    color: #00b38a;
    text-decoration: underline;

}


.container {
    display: flex;
    align-items: center;

    flex-wrap: nowrap;

    gap: 16px;
    margin-right: 350px;

}

/* 可以添加一个包含栏目、下载等链接的容器样式 */
.links-container {
    display: flex;
    align-items: center;
    /* 之间的间隔 */



}

;

/* Right Content Buttons */

.btn-login {
    background-color: transparent;
    /* 透明背景 */
    border: none;
    /* 无边框 */
    color: #666666;
    /* 文本颜色与下载链接一致 */
    padding: 0;
    /* 移除内边距 */
    font-size: 14px;
    font-weight: normal;
    /* 正常字体粗细 */
    cursor: pointer;
    text-decoration: none;
    /* 移除下划线 */
    transition: color 0.3s ease;
    /* 颜色过渡效果 */
}

.btn-register {
    background-color: transparent;
    /* 透明背景 */
    border: none;
    /* 无边框 */
    color: #666666;
    /* 文本颜色与下载链接一致 */
    padding: 0;
    /* 移除内边距 */
    font-size: 14px;
    font-weight: normal;
    /* 正常字体粗细 */
    cursor: pointer;
    text-decoration: none;
    /* 移除下划线 */
    transition: color 0.3s ease;
    /* 颜色过渡效果 */
    margin-left: 13px;
}

.lrcs {
    display: flex;
    align-items: center;

}

/* 添加伪类来模仿下载链接的hover效果 */
.btn-login:hover,
.btn-register:hover {
    color: #00b38a;
    /* 悬停时变为绿色 */
    text-decoration: underline;
    /* 悬停时添加下划线 */
}

/* User Info Styling */
.user-info {
    display: flex;
    align-items: center;
}

.user-info .user-avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    /* Circular avatar */
    object-fit: cover;

}

.user-info span {
    font-size: 14px;
    font-weight: 500;
    color: #333333;
}
</style>